// Copyright (c) Microsoft Corporation.  All rights reserved.

// This file contains several workarounds on inconsistent browser behaviors that administrators may customize.
"use strict";

// iPhone email friendly keyboard does not include "\" key, use regular keyboard instead.
// Note change input type does not work on all versions of all browsers.
if (navigator.userAgent.match(/iPhone/i) != null) {
    var emails = document.querySelectorAll("input[type='email']");
    if (emails) {
        for (var i = 0; i < emails.length; i++) {
            emails[i].type = 'text';
        }
    }
}

// In the CSS file we set the ms-viewport to be consistent with the device dimensions, 
// which is necessary for correct functionality of immersive IE. 
// However, for Windows 8 phone we need to reset the ms-viewport's dimension to its original
// values (auto), otherwise the viewport dimensions will be wrong for Windows 8 phone.
// Windows 8 phone has agent string 'IEMobile 10.0'
if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
    var msViewportStyle = document.createElement("style");
    msViewportStyle.appendChild(
        document.createTextNode(
            "@-ms-viewport{width:auto!important}"
        )
    );
    msViewportStyle.appendChild(
        document.createTextNode(
            "@-ms-viewport{height:auto!important}"
        )
    );
    document.getElementsByTagName("head")[0].appendChild(msViewportStyle);
}

// If the innerWidth is defined, use it as the viewport width.
if (window.innerWidth && window.outerWidth && window.innerWidth !== window.outerWidth) {
    var viewport = document.querySelector("meta[name=viewport]");
    viewport.setAttribute('content', 'width=' + window.innerWidth + 'px; initial-scale=1.0; maximum-scale=1.0');
}

// Gets the current style of a specific property for a specific element.
function getStyle(element, styleProp) {
    var propStyle = null;

    if (element && element.currentStyle) {
        propStyle = element.currentStyle[styleProp];
    }
    else if (element && window.getComputedStyle) {
        propStyle = document.defaultView.getComputedStyle(element, null).getPropertyValue(styleProp);
    }

    return propStyle;
}

// The script below is used for downloading the illustration image 
// only when the branding is displaying. This script work together
// with the code in PageBase.cs that sets the html inline style
// containing the class 'illustrationClass' with the background image.
var computeLoadIllustration = function () {
    var branding = document.getElementById("branding");
    var brandingDisplay = getStyle(branding, "display");
    var brandingWrapperDisplay = getStyle(document.getElementById("brandingWrapper"), "display");

    if (brandingDisplay && brandingDisplay !== "none" &&
        brandingWrapperDisplay && brandingWrapperDisplay !== "none") {
        var newClass = "illustrationClass";

        if (branding.classList && branding.classList.add) {
            branding.classList.add(newClass);
        } else if (branding.className !== undefined) {
            branding.className += " " + newClass;
        }
        if (window.removeEventListener) {
            window.removeEventListener('load', computeLoadIllustration, false);
            window.removeEventListener('resize', computeLoadIllustration, false);
        }
        else if (window.detachEvent) {
            window.detachEvent('onload', computeLoadIllustration);
            window.detachEvent('onresize', computeLoadIllustration);
        }
    }
};

if (window.addEventListener) {
    window.addEventListener('resize', computeLoadIllustration, false);
    window.addEventListener('load', computeLoadIllustration, false);
}
else if (window.attachEvent) {
    window.attachEvent('onresize', computeLoadIllustration);
    window.attachEvent('onload', computeLoadIllustration);
}

// ***** CNRSrhd begings here *****
/*
 Copyright (C) CNRS www.cnrs.fr
 Use JQUERY and easyAutoComplete to rebuild ADFS Realm Home Discovery Page
*/

// only display our UI when the bySelection div is not hidden
if (! isHidden(document.getElementById("bySelection"))) {
    // Anonymous "self-invoking" function
    (function () {
        // Dynamically load JS and CSS from http://jsfiddle.net/9N7Z2/3/ by http://facebook.com/anders.tornblad anders.tornblad@gmail.com
        // Load JQUERY
        var jqueryjs = document.createElement("SCRIPT");
        jqueryjs.src = '/adfs/portal/script/jquery-1.12.0.js';
        jqueryjs.type = 'text/javascript';
        document.getElementsByTagName("head")[0].appendChild(jqueryjs);
        
        // Load easyAutocomplete CSS
        var easycss = document.createElement("LINK");
        easycss.href = '/adfs/portal/css/easy-autocomplete.css';
        easycss.type = 'text/css';
        easycss.rel = 'stylesheet';
        document.getElementsByTagName("head")[0].appendChild(easycss);

        // Poll for jQuery to come into existance
        var checkReady = function (callback) {
            if (window.jQuery) {
                callback(jQuery);
            }
            else {
                window.setTimeout(function () { checkReady(callback); }, 20);
            }
        };

        // Start polling...
        checkReady(function ($) {
            $(function () {
                // build interface, 
                rhdUI();

                // Load easyAutocomplete JS
                $.ajax({
                    type: "GET",
                    url: "/adfs/portal/script/jquery.easy-autocomplete.js",
                    dataType: "script",
                    cache: true
                }).done(function () {
                    // build easyautpcomplete
                    var options = {

                        url: "/adfs/portal/script/disco.js",
                        getValue: "DisplayName",
                        template: {
                            type: "iconLeft",
                            fields: { iconSrc: "Logo" }
                        },
                        list: {
                            maxNumberOfElements: 10,
                            match: {
                                enabled: true
                            },
                            onSelectItemEvent: function () {
                                var value = $("#hrdInput").getSelectedItemData().entityID;
                                $("#hrdSelection").val(value).trigger("change");
                                $("#hrdSelection").attr("name", "HomeRealmSelection");
                            }
                        },
                        theme: "blue-light",
                        placeholder: "Type your IdP name !"
                    };
                    $('#hrdInput').easyAutocomplete(options);
                });
            });
        });
    })();
}

// build the new UI
function rhdUI() {

    // add a div for our use
    $("#bySelection").before('<div id="hrdCNRS"></div>');

    // add CNRS Idp
    $("#hrdCNRS").append('<div id="preferedIDP" style="border:2px solid blue"/>')
    $("#preferedIDP").append('<p>Cliquer le bouton suivant pour vous authentifier auprès de Janus, le fournisseur d\'identité du CNRS</p>');
    $("#preferedIDP").append('<div class="idp" id="idpJanus"><img class="largeIcon float" src="/adfs/portal/images/idp/localsts.png?id=A3911892BE04D81EBA5A8E0C74F77099AA1DB05E542FBFCC78C9DF4B0EC0E3A6" alt="Intégration Meudon" /><div class="idpDescription float"><span class="largeTextNoWrap indentNonCollapsible">Intégration Meudon</span></div></div>');
    $("#idpJanus").keypress(function () {
        if (event && (event.keyCode == 32 || event.keyCode == 13)) HRD.selection('https://idp.minte.dsi.cnrs.fr/idp/shibboleth');
    });
    $("#idpJanus").click(function() {
        HRD.selection('https://idp.minte.dsi.cnrs.fr/idp/shibboleth');
        return false;
    });
    
    // add Auto complete field
    $("#hrdCNRS").append('<p>Ou sélectionner votre fournisseur d\'identité en entrant son nom dans le champ ci-après. Une fois voytre sélection faite valider votre choix en cliquant sur le bouton valider</p><input id="hrdInput" type="text" size="45"><input type="submit" value="Valider">');
    
    // add homeless IdP (CRU account from RENATER)
    $("#hrdCNRS").append('<div id="homelessIDP" style="border:2px solid blue"/>')
    $("#homelessIDP").append('<p>Si vous n\'aveez pas de de fournissuer d\'identitité, vous pouvez utiliser votre compte CRU ou vous en créer un en suivant le lien suivant');
    $("#homelessIDP").append('<div class="idp" id="idpCRU"><img class="largeIcon float" src="/adfs/portal/images/idp/localsts.png?id=A3911892BE04D81EBA5A8E0C74F77099AA1DB05E542FBFCC78C9DF4B0EC0E3A6" alt="Intégration Meudon" /><div class="idpDescription float"><span class="largeTextNoWrap indentNonCollapsible">Intégration Meudon</span></div></div>');
    $("#idpCRU").keypress(function () {
        if (event && (event.keyCode == 32 || event.keyCode == 13)) HRD.selection('urn:mace:cru.fr:federation:sac');
    });
    $("#idpCRU").click(function () {
        HRD.selection('urn:mace:cru.fr:federation:sac');
        return false;
    });
    
    // hide adfs default div
    $('#bySelection').hide();
};

// check if en element is hidden, just to load Jquery
function isHidden(el) {
    // from http://stackoverflow.com/questions/19669786/check-if-element-is-visible-in-dom
    return (el.offsetParent === null)
}
